package com.ywu.data.source.standard.source;

import com.ywu.data.source.standard.dto.YwuDataTableFieldDto;
import com.ywu.data.source.standard.entity.YwuDataExecEntity;
import com.ywu.data.source.standard.entity.YwuDataSourceEntity;
import com.ywu.data.source.standard.entity.YwuDataTableEntity;
import com.ywu.data.source.standard.source.field.YwuBuildFieldCommon;
import com.ywu.data.source.standard.source.jdbc.JdbcUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.sql.Connection;
import java.util.List;
import java.util.Map;

/**
 * @ClassName YwuExecSqlCoreMySql
 * @Description TODO
 * @Author GroundDemo
 * @Date 2024/10/26 10:33
 * @Version 1.0
 **/
@Component
@Slf4j
public class YwuExecSqlCoreMySql implements YwuExecSqlCore {
    private static final String DATA_SOURCE_TYPE_MYSQL = "MySQL";

    @Autowired
    private JdbcUtil jdbcUtil;

    @Autowired
    private YwuBuildFieldCommon ywuBuildFieldCommon;

    @Override
    public String dataSourceType() {
        return DATA_SOURCE_TYPE_MYSQL;
    }

    /**
    * @Author GroundDemo
    * @Description 创建Mysql数据源
    * @Date 10:34 2024/10/26
    * @Param [entity]
    * @return void
    **/
    @Override
    public void createDataSource(YwuDataSourceEntity entity) {
        // 获取连接
        Connection connect = jdbcUtil.getConnect(entity.getDataSourceType(), "");
        String createDataSourceSql = String.format("CREATE DATABASE `%s` CHARACTER SET '%s';",
                entity.getTenantId() + "_" + entity.getCode(), entity.getSourceEncode());
        jdbcUtil.execDataSource(connect, createDataSourceSql);
    }

    /**
    * @Author GroundDemo
    * @Description 修改Mysql数据源
    * @Date 10:34 2024/10/26
    * @Param [entity]
    * @return void
    **/
    @Override
    public void updateDataSource(YwuDataSourceEntity entity) {
        // 获取连接
        Connection connect = jdbcUtil.getConnect(entity.getDataSourceType(), "");
        String createDataSourceSql = String.format("ALTER DATABASE `%s` CHARACTER SET '%s';",
                entity.getTenantId() + "_" + entity.getCode(), entity.getSourceEncode());
        jdbcUtil.execDataSource(connect, createDataSourceSql);
    }

    /**
    * @Author GroundDemo
    * @Description 删除Mysql数据源
    * @Date 10:34 2024/10/26
    * @Param [entity]
    * @return void
    **/
    @Override
    public void deleteDataSource(YwuDataSourceEntity entity) {
        // 获取连接
        Connection connect = jdbcUtil.getConnect(entity.getDataSourceType(), "");
        String createDataSourceSql = String.format("DROP DATABASE `%s`;", entity.getTenantId() + "_" + entity.getCode());
        jdbcUtil.execDataSource(connect, createDataSourceSql);
    }

    /**
    * @Author GroundDemo
    * @Description 创建数据表
    * @Date 17:35 2024/10/28
    * @Param [ywuDataTableEntity]
    * @return void
    **/
    @Override
    public void createTable(YwuDataTableEntity ywuDataTableEntity) {
        StringBuilder resSql = new StringBuilder();
        // 获取连接
        Connection connect = jdbcUtil.getConnect(ywuDataTableEntity.getDataSourceType(),
                ywuDataTableEntity.getTenantId() + "_" + ywuDataTableEntity.getDataSourceCode());
        // 构建sql
        String beginSql = String.format("CREATE TABLE `%s` (", ywuDataTableEntity.getTableName());
        String endSql = String.format(") ENGINE=%s;", ywuDataTableEntity.getEngineName());
        // 获取每个字段的sql数据
        resSql.append(beginSql);
        List<YwuDataTableFieldDto> fieldInfo = ywuDataTableEntity.getFieldInfo();
        for (int index = 0; index < fieldInfo.size(); index++) {
            YwuDataTableFieldDto field = fieldInfo.get(index);
            resSql.append(ywuBuildFieldCommon.buildFieldInfoSql(ywuDataTableEntity, field));
            if (index != fieldInfo.size() - 1) {
                resSql.append(",\n");
            }
        }
        resSql.append(endSql);
        jdbcUtil.execDataSource(connect, resSql.toString());
    }

    /**
    * @Author GroundDemo
    * @Description 修改数据表
    * @Date 17:35 2024/10/28
    * @Param [ywuDataTableEntity]
    * @return void
    **/
    @Override
    public void updateTable(YwuDataTableEntity oldEntity, YwuDataTableEntity newEntity) {
        // 获取连接
        Connection connect = jdbcUtil.getConnect(newEntity.getDataSourceType(),
                newEntity.getTenantId() + "_" + newEntity.getDataSourceCode());
        // 比较新旧的表名称是否一致
        if (!oldEntity.getTableName().equals(newEntity.getTableName())) {
            String renameSql = ywuBuildFieldCommon.renameTableNameSql(oldEntity, newEntity);
            // 执行sql
            jdbcUtil.execDataSource(connect, renameSql);
        }
        String startSql = String.format("ALTER TABLE `%s` ", newEntity.getTableName());
        String endSql = String.format("ENGINE = %s;", newEntity.getEngineName());
        String resSql = "";
        resSql += startSql;
        // 比较字段数据是否需要修改
        Map<String, List<YwuDataTableFieldDto>> compareEntityMap = ywuBuildFieldCommon.compareField(oldEntity, newEntity);
        // 标志位，是否需要执行核心sql
        boolean flag = false;
        // 生成删除sql
        List<YwuDataTableFieldDto> deleteList = compareEntityMap.get("delete");
        if (!CollectionUtils.isEmpty(deleteList)) {
            flag = true;
            resSql += ywuBuildFieldCommon.buildDeleteColFieldInfoSql(deleteList);
        }
        // 生成新增sql
        List<YwuDataTableFieldDto> addList = compareEntityMap.get("add");
        if (!CollectionUtils.isEmpty(addList)) {
            flag = true;
            resSql += ywuBuildFieldCommon.buildAddColFieldInfoSql(addList, newEntity);
        }
        // 生成修改的sql
        List<YwuDataTableFieldDto> updateList = compareEntityMap.get("update");
        if (!CollectionUtils.isEmpty(updateList)) {
            flag = true;
            resSql += ywuBuildFieldCommon.buildUpdateColFieldInfoSql(updateList, newEntity);
        }
        if (!flag) {
            return;
        }
        resSql += endSql;
        jdbcUtil.execDataSource(connect, resSql);
    }

    /**
    * @Author GroundDemo
    * @Description 删除数据表
    * @Date 17:35 2024/10/28
    * @Param [ywuDataTableEntity]
    * @return void
    **/
    @Override
    public void deleteTable(YwuDataTableEntity ywuDataTableEntity) {
        // 获取连接
        Connection connect = jdbcUtil.getConnect(ywuDataTableEntity.getDataSourceType(),
                ywuDataTableEntity.getTenantId() + "_" + ywuDataTableEntity.getDataSourceCode());
        String dropSql = String.format("DROP TABLE `%s` ;", ywuDataTableEntity.getTableName());
        jdbcUtil.execDataSource(connect, dropSql);
    }

    /**
    * @Author GroundDemo
    * @Description 插入数据
    * @Date 14:17 2024/11/20
    * @Param [ywuDataExecEntity]
    * @return void
    **/
    @Override
    public void insertIntoInfo(YwuDataExecEntity ywuDataExecEntity) {
        // 获取连接
        Connection connect = jdbcUtil.getConnect(ywuDataExecEntity.getDataSourceType(),
                ywuDataExecEntity.getDataSourceTenantId() + "_" + ywuDataExecEntity.getDataSourceCode());
        // 预处理sql
        jdbcUtil.execSql(connect, ywuDataExecEntity.getExecSql(), "INSERT", ywuDataExecEntity);
    }

    /**
    * @Author GroundDemo
    * @Description 删除数据
    * @Date 14:17 2024/11/20
    * @Param [ywuDataExecEntity]
    * @return void
    **/
    @Override
    public void deleteInfo(YwuDataExecEntity ywuDataExecEntity) {
        // 获取连接
        Connection connect = jdbcUtil.getConnect(ywuDataExecEntity.getDataSourceType(),
                ywuDataExecEntity.getDataSourceTenantId() + "_" + ywuDataExecEntity.getDataSourceCode());
        // 预处理sql
        jdbcUtil.execSql(connect, ywuDataExecEntity.getExecSql(), "DELETE", ywuDataExecEntity);
    }

    /**
    * @Author GroundDemo
    * @Description 修改数据
    * @Date 14:17 2024/11/20
    * @Param [ywuDataExecEntity]
    * @return void
    **/
    @Override
    public void updateInfo(YwuDataExecEntity ywuDataExecEntity) {
        // 获取连接
        Connection connect = jdbcUtil.getConnect(ywuDataExecEntity.getDataSourceType(),
                ywuDataExecEntity.getDataSourceTenantId() + "_" + ywuDataExecEntity.getDataSourceCode());
        // 预处理sql
        jdbcUtil.execSql(connect, ywuDataExecEntity.getExecSql(), "UPDATE", ywuDataExecEntity);
    }

    /**
    * @Author GroundDemo
    * @Description 查询数据
    * @Date 14:17 2024/11/20
    * @Param [ywuDataExecEntity]
    * @return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
    **/
    @Override
    public List<Map<String, Object>> queryInfo(YwuDataExecEntity ywuDataExecEntity) {
        // 获取连接
        Connection connect = jdbcUtil.getConnect(ywuDataExecEntity.getDataSourceType(),
                ywuDataExecEntity.getDataSourceTenantId() + "_" + ywuDataExecEntity.getDataSourceCode());
        // 预处理sql
        return jdbcUtil.execQuery(connect, ywuDataExecEntity.getExecSql(), ywuDataExecEntity);
    }

    /**
    * @Author GroundDemo
    * @Description 复杂查询
    * @Date 15:52 2025/9/13
    * @Param [ywuDataExecEntity]
    * @return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
    **/
    @Override
    public List<Map<String, Object>> complexQueryInfo(YwuDataExecEntity ywuDataExecEntity) {
        // 获取连接
        Connection connect = jdbcUtil.getConnect(ywuDataExecEntity.getDataSourceType(),
                ywuDataExecEntity.getDataSourceTenantId() + "_" + ywuDataExecEntity.getDataSourceCode());
        // 预处理sql
        return jdbcUtil.execComplexQuery(connect, ywuDataExecEntity.getExecSql(), ywuDataExecEntity);
    }
}
